package com.gzzz.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    public static Connection conn;
    static PreparedStatement preSQL;
    public static void getConnection() {
        //1.从类路径下加载配置文件，获取一个输入流。
        InputStream inputStream = DBUtils.class.getResourceAsStream("/druid.properties");
        //2.使用Properties对象的方法将配置文件中属性加载到Properties对象中
        Properties properties = new Properties();
        //加载了配置文件中所有的属性
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataSource dataSource = null;
        try {
            //3.通过druid的工厂类创建连接池
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            //4.从连接池中获取连接对象
            conn=dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 通过前端传输的数据返回该条数据主键
    public static int insert(String s) {
        String insertSQL = "INSERT INTO kwic(`lines`) VALUES( ? )";
        Integer id = 0; //  该条数据的主键id
        //调用上面自己封装的getConnection方法连接数据库
        getConnection();
        try {
            //通过预处理对象处理sql语句
            preSQL =conn.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
            preSQL.setString(1 , s);
            // 执行插入语句
            preSQL.executeUpdate();
            // 主键回显
            ResultSet rsKeys = preSQL.getGeneratedKeys();
            rsKeys.next();
            // 返回主键值
            id = rsKeys.getInt(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }
    public static InputStream select(Integer rid) {
        String selectSQL = "SELECT * FROM kwic WHERE id = ? ";
        ResultSet rs = null;
        InputStream inputStream = null;
        //调用上面自己封装的getConnection方法连接数据库
        getConnection();
        //通过预处理对象处理sql语句
        try {
            preSQL =conn.prepareStatement(selectSQL);
            preSQL.setInt(1 , rid);
            //获取结果集对象
            rs= preSQL.executeQuery();
            //将rs转换为字符流
            while (rs.next()){
                byte[] bytes = rs.getString("lines").getBytes();//将字符串转换为字节数组
                inputStream = new ByteArrayInputStream(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回字符流
        return inputStream;
    }

}
